package output

import "github.com/kataras/iris"

/**
 * 封装的输出类，返回指定的格式信息
 */

const (
	STATUS_SUCCESS = 200 //成功
	STATUS_ERROR   = 400 //失败
)

// 输出结构体
type Output struct {
	code    int
	message string
	data    interface{}
	Ctx     iris.Context
}

// 输出成功
func (op *Output) Success(data interface{}) {
	op.code = STATUS_SUCCESS
	op.message = "ok"
	op.data = data

	_, _ = op.Ctx.JSON(op.getAllData())
}

// 输出标准错误
func (op *Output) Message(message string) {
	op.code = STATUS_ERROR
	if message != "" {
		op.message = message
	} else {
		op.message = "error"
	}

	_, _ = op.Ctx.JSON(op.getAllData())
}

// 输出指定状态错误
func (op *Output) Error(code int, message string) {
	op.code = code
	if message != "" {
		op.message = message
	} else {
		op.message = "error"
	}

	_, _ = op.Ctx.JSON(op.getAllData())
}

// 组装为指定格式的基础数据
func (op *Output) getAllData() map[string]interface{} {
	data := make(map[string]interface{})
	data["message"] = op.message
	data["code"] = op.code
	data["data"] = op.data

	return data
}
